var _ = (function () {
	var util = {};
	['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'].forEach(function (value, i) {
		util['is' + value] = function (obj) {
			return Object.prototype.toString.call(obj) === '[object ' + value + ']';
		}
	});
	return util;
}());

(function ($) {
	$.versions = (function (navigator) {
		var u = navigator.userAgent.toLowerCase(), app = navigator.appVersion;
		return {
			trident: u.indexOf('trident') > -1, //IE内核
			presto: u.indexOf('presto') > -1, //opera内核
			webKit: u.indexOf('applewebkit') > -1, //苹果、谷歌内核
			gecko: u.indexOf('gecko') > -1 && u.indexOf('khtml') == -1,//火狐内核
			mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i), //ios终端
			android: u.indexOf('android') > -1 || u.indexOf('linux') > -1, //android终端或者uc浏览器
			iPhone: u.indexOf('iphone') > -1, //是否为iPhone或者QQHD浏览器
			iPad: u.indexOf('ipad') > -1, //是否iPad
			webApp: u.indexOf('safari') == -1, //是否web应该程序，没有头部与底部
			pad: u.indexOf("pad") > -1,
			wx: u.indexOf("micromessenger") > -1
		};
	}(navigator));

	$.downurl = {
		ios: "http://a.app.qq.com/o/simple.jsp?pkgname=com.youlijinfu.android",
		android: "http://a.app.qq.com/o/simple.jsp?pkgname=com.youlijinfu.android"
	}

	$.getRequest = function () {
		var url = location.search.toLowerCase();
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substr(1);
			var strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	};

}(Zepto));

var h5ajax = (function ($) {
	function Ajax(options) {
		var deferred = $.Deferred && $.Deferred();
		var settings = $.extend({ dataType: 'JSON', responseType: 'JSON', method: 'GET' }, options || {});

		if (!settings.url) {
			return new Error('request url is undefined');
		}
		settings.url = /^(http|https)\/\/:/.test(settings.url) ? settings.url : h5Config.baseurl + settings.url;

		var xhr = new XMLHttpRequest();
		xhr.open(settings.method.toUpperCase(), settings.url);
		if (deferred) deferred.promise(xhr);

		settings.headers = settings.headers || {};
		if (!settings.headers['Accept']) {
			settings.headers['Accept'] = 'application/json, text/plain, */*';
		}
		if (settings.method.toLowerCase() != 'get' && !settings.headers['Content-Type']) {
			settings.headers['Content-Type'] = 'application/x-www-form-urlencoded';
		}
		//for (var )
		var paramsQuery = [];
		if (settings.data && settings.dataType.toUpperCase() === 'JSON') {
			for (var key in settings.data) {
				paramsQuery.push(key + '=' + settings.data[key]);
			}
			settings.data = paramsQuery.join('&');
		}

		for (var key in settings.headers) {
			xhr.setRequestHeader(key, settings.headers[key]);
		}

		xhr.onload = function () {
			var status = xhr.status;
			var statusText = xhr.statusText;
			var response = typeof xhr.response === 'undefined' ? xhr.responseText : xhr.response;
			if (settings.responseType.toLowerCase() === 'json') {
				response = JSON.parse(response);
			}
			if (status >= 200 && status < 300) {
				deferred.resolveWith(null, [response, status, xhr])
			} else {
				deferred.rejectWith(null, [statusText, status, xhr])
			}
		};
		xhr.send(settings.data || null);
		return xhr;

	}
	return function (options) {
		var u_id = storage.get('u_uid');
		var terminal = 'wei';
		var sourcetypeid = storage.get('sourcetypeid');

		if (!options.data) {
			if (!options.dataType || options.dataType.toUpperCase() == 'JSON') {
				options.data = {};
			} else if (options.dataType.toUpperCase() == 'FORMDATA') {
				options.data = new FormData();
			} else {
				options.data = '';
			}
		}

		if (Object.prototype.toString.call(options.data) === '[object FormData]') {
			options.data.append('u_id', u_id);
			options.data.append('terminal', terminal);
			options.data.append('sourcetypeid', sourcetypeid);
		} else if (typeof options.data === 'string') {
			options.data += '&u_id=' + u_id + '&terminal=' + terminal + '&sourcetypeid=' + sourcetypeid;
		} else {
			options.data.u_id = u_id;
			options.data.terminal = terminal;
			options.data.sourcetypeid = sourcetypeid;
		}
		return Ajax(options);
		//return Ajax;
	}
}(Zepto));

var storage = (function () {
	var prefix = 'ls.';
	var deriveQualifiedKey = function (key) {
		return prefix + key;
	};
	var sto = {
		set: function (key, value) {
			if (!key) {
				throw new Error('set storage : empty key');
			}
			if (typeof value !== 'undefined') {
				value = JSON.stringify(value);
				localStorage.setItem(deriveQualifiedKey(key), value);
			}
			return this;
		},
		setJsonStorage: function (key, value) {
			if (typeof value !== 'undefined') {
				value = { data: value };
			}
			return sto.set(key, value);
		},
		get: function (key) {
			if (key) {
				var item = localStorage.getItem(deriveQualifiedKey(key));
				if (item) {
					return JSON.parse(item);
				}
			}
			return null;
		},
		getJsonStorage: function (key) {
			var item = sto.get(key);
			if (item && item.data) {
				return item.data;
			}
			return item;
		},
		has: function (key) {
			return Object.prototype.hasOwnProperty(localStorage, deriveQualifiedKey(key));
		},
		remove: function (key) {
			if (sto.has(key)) {
				localStorage.removeItem(deriveQualifiedKey(key));
			}
		}
	}
	return sto;
}());



$(function () {
	var afs_token;
	pointman.use('do', function () {
		var afs = pointman.getConfig();
		var afs_appkey = afs.appkey;
		var afs_scene = afs.scene;
		afs_token = afs.token;
	});
	// 获取路径中的fullname
	var sharecode = ''
	var num = location.search.indexOf('getsharecode=');
	var and = location.search.indexOf('&') != -1 ? location.search.indexOf('&') : location.href.length;
	if (num != -1) {
		sharecode = location.search.substring(num + 'getsharecode='.length, and)//截取url中分享码
		if (sharecode == 'undefined') {
			sharecode = ''
		}
		h5ajax({
			url: '/api/share/getsharefullname?code=' + sharecode,
			method: 'GET',
			data: {

			}
		}).then(function (res) {
			if (res.code == 1) {
				$('#invitename').html('您的好友' + res.data + '送来11888体验金和200元专属红包， 快来与TA一起赚钱吧！')
			}
		}).fail(function (error) {

		});
	}
	$('#verifyTimer').hide();
	var params = $.getRequest();
	var sourcetypeid = params['sourcetypeid'] || storage.getJsonStorage("sourcetypeid");
	if (sourcetypeid) {
		h5ajax({
			url: '/api/source/GetSourceTypeIdByName?name=' + sourcetypeid,
			method: 'GET',
			data: {
				name: sourcetypeid
			}
		}).then(function (res) {
			storage.set('sourcetypeid', res);
		}).fail(function (error) {

		});
	}
	// $('input').on('touchstart', function () {
	// 	layer.closeAll();
	// });
	var isGetVer = true, isSendVerify = true;
	$('#verifyBtn').on("click", function () {//获取验证码
		if (isGetVer && isSendVerify) {
			var txtRegisterMobile = $('#txtRegisterMobile').val();
			if (!mobileReg.test(txtRegisterMobile)) {
				layer.open({
					content: '请输入正确的手机号', skin: 'msg', time: 2
				});
				return;
			}
			isSendVerify = false;
			layer.open({ type: 2, shade: true });//打开loading
			h5ajax({
				url: '/api/User/GetMobileVerifyCode',
				method: 'POST',
				data: {
					mobile: txtRegisterMobile,
					IsExistUser: 0,
					tokenId: afs_token
				}
			}).then(function (res) {
				layer.closeAll();
				if (res.code == 1) {//倒计时 //重新获取验证码
					verifyNum = 60;
					isGetVer = false;
					isVerify = true;
					$('#verifyBtn').hide();
					$('#verifyTimer').text("60s").show();
					var verifyInter = setInterval(function () {
						verifyNum--;
						if (verifyNum == 0) {
							clearInterval(verifyInter);
							isGetVer = true;
							isSendVerify = true;
							$('#verifyBtn').text('重新获取').show();
							$('#verifyTimer').hide();
						} else {
							$('#verifyTimer').text(verifyNum + "s").show();
						}
					}, 1000);
				} else if (res.code == 1083) {
					isSendVerify = true;
					var html = '';
					html += '<div class="td_bg">';
					html += '     <span class="td_close">';
					html += '    </span>';
					html += '</div>';
					layer.open({
						type: 1,
						shade: false,
						title: false,
						content: html
					});
					var Tdparent = document.querySelector('.td_bg');
					var Tdclose = document.querySelector('.td_close');
					Tdparent.parentNode.parentNode.style.background = "rgba(255,255,255,0)";
					Tdparent.parentNode.parentNode.style.boxShadow = 'none'
					Tdclose.onclick = function () {
						layer.closeAll();
					}
				} else if (res.code == 107) {
					isSendVerify = true;
					var html = '';
					html += '<div class="td_bg1">';
					html += ' <img class="td_close1" src="https://file.youlijinfu.com/images/hd/invitereg/close.png">'
					html += ' <img class="td_btn td_btn_down" src="https://file.youlijinfu.com/images/hd/invitereg/button_05.png">'
					html += ' <img class="td_btn td_btn_login" src="https://file.youlijinfu.com/images/hd/invitereg/button_06.png">'
					html += '</div>'
					layer.open({
						type: 1,
						shade: true,
						title: false,
						content: html
					});
					$('.td_btn_down').on("click", function () {
						if ($.versions.ios) {
							window.location.href = $.downurl.ios;
						} else {
							window.location.href = $.downurl.android;
						}
					})
					$('.td_btn_login').on("click", function () {
						window.location.href = '/login/index';
					})
					$('.td_close1').on("click", function () {
						layer.closeAll();
					});

				} else {
					isSendVerify = true;
					layer.open({
						content: res.data, skin: 'msg', time: 2 //2秒后自动关闭
					});
				}
			}).fail(function (error) {
				layer.closeAll();
				layer.open({ content: '获取验证码失败', skin: 'msg', time: 2 })
			});
		}
	});
	var isVerify = false;//判断是否获验证码
	var mobileReg = /1[3-9]{1}[0-9]{9}/;//正则验证input
	var verifyCodeReg = /\d{5}/;
	var passwordReg = /\S{6,20}/;

	var validRegister = function () {
		var txtRegisterMobile = $('#txtRegisterMobile').val();
		var txtVerifyCode = $('#txtVerifyCode').val();
		var txtRegisterPwd = $('#txtRegisterPwd').val();

		if (!mobileReg.test(txtRegisterMobile)) {
			layer.open({
				content: '请输入正确的手机号', skin: 'msg', time: 2
			});
			return false;
		}
		if (!isVerify) {
			layer.open({
				content: '请先获取短信验证码', skin: 'msg', time: 2
			});
			return false;
		}
		if (!verifyCodeReg.test(txtVerifyCode)) {
			layer.open({
				content: '短信验证码错误', skin: 'msg', time: 2
			});
			return false;
		}
		if (!passwordReg.test(txtRegisterPwd) || /(\s|[\u4E00-\u9FA5])/.test(txtRegisterPwd)) {
			layer.open({
				content: '请设置6-20位登录密码', skin: 'msg', time: 2
			});
			return false;
		}
		if ($("#agree").hasClass('a_b_i_bor')) {
			layer.open({
				content: '请先同意有利金服用户协议', skin: 'msg', time: 2
			})
			return false
		}
		return true;
	}
	//选择同意有利金服协议
	var agree = $("#agree");
	agree.on("click", function () {
		if (agree.hasClass('a_b_i_bor')) {
			agree.removeClass("a_b_i_bor")
		} else {
			agree.addClass("a_b_i_bor")
		}
	})
	// getsharecode

	var isRegister = true;
	$('#btn_register').click(function () {
		localStorage.clear();
		// 清除当前浏览器所有缓存
		if (!isRegister) {
			return;
		}
		var mobile = $('#txtRegisterMobile').val();
		var verifyCode = $('#txtVerifyCode').val();
		var password = $('#txtRegisterPwd').val();

		if (!validRegister()) {
			return;
		}
		var sharecode = ''
		var num = location.search.indexOf('getsharecode=');
		var and = location.search.indexOf('&') != -1 ? location.search.indexOf('&') : location.href.length;
		if (num != -1) {
			sharecode = location.search.substring(num + 'getsharecode='.length, and)//截取url中分享码
			if (sharecode == 'undefined') {
				sharecode = ''
			}
		}
		isRegister = false;
		layer.open({ type: 2 });
		h5ajax({
			url: '/api/user/Register',
			method: 'POST',
			data: {
				userfromid: 0,
				username: mobile,
				password: password,
				verifycode: verifyCode,
				clientId: '',
				geTuiAppId: '',
				invitationcode: sharecode,//分享码,
				tokenId: afs_token

			}
		}).then(function (res) {
			if (res.code == 1) {
				var data = res.data;
				
				storage.set('u_uid', {'data':data.gid});
				storage.set('user', data.userInfo);
				setTimeout(function () {
					window.location.href = "/spread/invitesuccess.html";
				}, 50);
			} else {
				isRegister = true;
				layer.closeAll();
				if (res.code == 1083) {//同盾弹框
					var html = '';
					html += '<div class="td_bg">';
					html += '     <span class="td_close">';
					html += '    </span>';
					html += '</div>';
					layer.open({
						type: 1,
						shade: false,
						title: false,
						content: html
					});
					var Tdparent = document.querySelector('.td_bg');
					var Tdclose = document.querySelector('.td_close');
					Tdparent.parentNode.parentNode.style.background = "rgba(255,255,255,0)";
					Tdparent.parentNode.parentNode.style.boxShadow = 'none'
					Tdclose.onclick = function () {
						layer.closeAll();
					}
				} else {
					layer.open({
						content: res.data, skin: 'msg', time: 2 //2秒后自动关闭
					});
				}
			}
		}).fail(function (err) {
			isRegister = true;
			layer.closeAll();
			layer.open({ content: '请求失败', skin: 'msg', time: 2 });
		});
	});


	$('[backtop]').click(function () {
		var top = $(this).attr('backtop') || 0;
		var scrollSeletor = $(this).attr('scroll');
		if (!scrollSeletor) {
			window.scrollTo(0, 0);
		} else {
			var offsetTop = $(scrollSeletor).offset().top;
			window.scrollTo(0, offsetTop - parseInt(top));
		}
	});
	// 立即使用
	$('#regsuccess').on("click", function () {
		window.location.href = '/mine/youliweal/experience';
	})
	if(storage.get('u_uid')){
		h5ajax({
			url: '/api/user/GetOfferRegisterAfter?u_id='+storage.get('u_uid').data,
			method: 'get',
			data: {
			}
		}).then(function (res) {
			if (res.code == 1) {
				var severseTime = new Date(res.data.replace(/-/g, '/')).getTime();
				var newdata = new Date(severseTime);
				var month = newdata.getMonth() + 1;
				var date = newdata.getDate()
				month < 10 ? month = '0' + month : month;
				date < 10 ? date = '0' + date : date;
				day = newdata.getFullYear() + '.' + month + '.' + date;
				$('#time').text("有效期：" + day);
				$('#redtime').text("有效期：" + day);
			} else {
	
			}
		}).fail(function (err) {
			layer.open({ content: '请求失败', skin: 'msg', time: 2 });
		});
	}
});
